package com.lunhui.service.provider.filter;

import com.alibaba.fastjson.JSONObject;
import com.lunhui.cache.client.model.LoginUserDto;
import com.lunhui.service.lunhui.service.business.CacheService;
import com.lunhui.service.lunhui.service.business.enums.ResultCodeEnum;
import com.lunhui.service.provider.common.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "ajaxFilter")
public class AjaxFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(AjaxFilter.class);
    @Autowired
    @Qualifier("cacheService")
    private CacheService cacheService;

    private final static ArrayList<String> pathList = new ArrayList<>(Arrays.asList(
            "/map/sceneMapInfo","/map/monsterMapInfo",
            "/rose/login",
            "/user/roseNameListInfo","/user/createRose"
            ));

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse=(HttpServletResponse)servletResponse;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");

        HttpServletRequest httpReq = (HttpServletRequest)servletRequest;

        String requestPath = httpReq.getRequestURI();
        if (pathList.contains(requestPath)) {
            Map<String, String[]> parameterMap = httpReq.getParameterMap();

            if (StringUtils.isEmpty(parameterMap.get("token")) || StringUtils.isEmpty(parameterMap.get("userId"))) {
                return;
            }

            String token = parameterMap.get("token")[0];
            String userId = parameterMap.get("userId")[0];

            int checkResult = isRightToken(token, Integer.parseInt(userId));
            if (checkResult == ResultCodeEnum.EXCEPTION_CODE.getCode()) {
                return;
            }

            if (checkResult == 0) {
                return;
            }

        }

        filterChain.doFilter(servletRequest,httpServletResponse);
    }

    @Override
    public void destroy() {

    }

    // checkToken
    private int isRightToken(String token, Integer userId) {
        try {
            LoginUserDto loginUser = cacheService.getLoginUserCacheByUserId(userId);

            if (loginUser == null) {
                return ResultCodeEnum.EXCEPTION_CODE.getCode();
            }

            String source = encodeToken(userId.toString(), loginUser.getCreateTime(), loginUser.getLastLoginTime());

            if (token.equals(source)) {
                return 1;
            } else {
                return 0;
            }

        } catch (Exception e) {
            logger.error("获取用户缓存信息失败: " + e.getMessage());
            return ResultCodeEnum.EXCEPTION_CODE.getCode();
        }
    }

    // encode
    private String encodeToken(String... strings) {
        StringBuilder sourceStr = new StringBuilder();

        for (String i : strings) {
            sourceStr.append(i);
        }

        return DigestUtils.md5Hex(sourceStr.toString());
    }


}